/*-
 * Copyright (c) 2006, 2007 FTS Team
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the FTS Team nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *      XMLConfigHandler.cpp
 *
 * $FTS$
 */

// Local Includes
#include <XMLConfigHandler.hpp>

#include <IRConfig.hpp>
#include <strings.h>

namespace FTSS // FullTextSearchSystem
{
#define C_STORAGE_NULLSTATE 0x00000001
#define C_STORAGE_IR_CONFIG 0x00000001
#define C_INDEXER_IR_CONFIG 0x00000002
#define C_PLAIN_IR_CONFIG   0x00000003

//
// Constructor
//
XMLConfigHandler::XMLConfigHandler(IRConfig & oIIRConfig): oIRConfig(oIIRConfig),
                                                           iParserState(C_STORAGE_NULLSTATE),
                                                           iHasTags(0)
{
	;;
}

//
// A destructor
//
XMLConfigHandler::~XMLConfigHandler() throw() { ;; }

//
// Start of XML Element
//
INT_32 XMLConfigHandler::StartElement(CCHAR_P         sElement,
                                      const UINT_32 & iLevel,
                                      const XMLAttr * aAttr,
                                      const UINT_32 & iAttributes,
                                      const UINT_32 & iLine,
                                      const UINT_32 & iColumn) throw()
{
	try
	{
		sElementContents.erase();
		if (iLevel == 1)
		{
			vStack.push_back(sElement);
		if (strcasecmp(sElement, "Storage") == 0)
			{
				iParserState = C_STORAGE_IR_CONFIG;
				}
			else if (strcasecmp(sElement, "Indexer")          == 0)
			{
			iParserState = C_INDEXER_IR_CONFIG;
				}
			else if (strcasecmp(sElement, "QueryParser")      == 0)
			{
				iParserState = C_PLAIN_IR_CONFIG;
			}
			else if (strcasecmp(sElement, "Retriever")        == 0)
			{
				iParserState = C_PLAIN_IR_CONFIG;
			}
			else if (strcasecmp(sElement, "Ranker")           == 0)
			{
				iParserState = C_PLAIN_IR_CONFIG;
			}
			else if (strcasecmp(sElement, "SnippetCollector") == 0)
			{
				iParserState = C_PLAIN_IR_CONFIG;
			}
			else { return -1; }
		}
		else if (iLevel >= 2 && iParserState == C_PLAIN_IR_CONFIG)
		{
			vStack.push_back(sElement);
		}
		else if (iLevel == 2)
		{
/*			else if (strcasecmp(sElement, "InvIndex
			else if (strcasecmp(sElement, "DocumentStorage
			else if (strcasecmp(sElement, "DocumentProperties
			else if (strcasecmp(sElement, "Parser
			else if (strcasecmp(sElement, "PlaintextParser
			else if (strcasecmp(sElement, "HTMLParser
			else if (strcasecmp(sElement, "QuorumSoftness
			else if (strcasecmp(sElement, "StopWordWeight

			else if (strcasecmp(sElement, "MaxResults
			else if (strcasecmp(sElement, "MinGoodResults
			else if (strcasecmp(sElement, "RandomizeW

			else if (strcasecmp(sElement, "DocumentFrameSize
			else if (strcasecmp(sElement, "Zones>
			RankTFIDF>
			RankPassage>
			MaxSnippets
			MaxSnippetLength
			HighlightTag
*/
		}
	}
	catch (...) { return -1; }

return 0;
}

//
// Create key for config from current stack
//
STLW::string XMLConfigHandler::CreateKeyFromStack()
{
	UINT_32 iStackSize = vStack.size();

	if (iStackSize == 1) { return vStack[0]; }

	if (iStackSize > 1)
	{
		STLW::string sResult(vStack[0]);
		for(UINT_32 iI = 1; iI < iStackSize; ++iI)
		{
			sResult.append("/");
			sResult.append(vStack[iI]);
		}
		return sResult;
	}

return "";
}

//
// Check contents of element and
//
INT_32 XMLConfigHandler::CheckElementContents()
{
	UINT_32 iI = 0;
	while (iI < sElementContents.size())
	{
		if (sElementContents[iI] != ' ' && sElementContents[iI] != '\t' && sElementContents[iI] != '\r' && sElementContents[iI] != '\n') { return 0; }
		++iI;
	}
return -1;
}

//
// Remove element from stack
//
void XMLConfigHandler::PopStackElement()
{
	UINT_32 iStackSize = vStack.size();
	if (iStackSize != 0)
	{
		--iStackSize;
		STLW::vector<STLW::string> vTMP;
		for(UINT_32 iI = 0; iI < iStackSize; ++iI)
		{
			vTMP.push_back(vStack[iI]);
		}
		vStack.swap(vTMP);
	}
}

//
// End of XML Element
//
INT_32 XMLConfigHandler::EndElement(CCHAR_P         sElement,
                                    const UINT_32 & iLevel,
                                    const UINT_32 & iLine,
                                    const UINT_32 & iColumn)   throw()
{
	try
	{
		if (iParserState == C_PLAIN_IR_CONFIG)
		{
			if (sElementContents.size() != 0 && CheckElementContents() == 0)
			{
				oIRConfig.AddKey(CreateKeyFromStack(), sElementContents);
			}
		}
		else if (iLevel == 1)
		{
			;;
		}
		else if (iLevel == 2)
		{
			if (iParserState == C_INDEXER_IR_CONFIG)
			{
				if (strcasecmp(sElement, "Parser")        == 0) { oIRConfig.AddKey("Indexer/Parser", sElementContents); }
			}
		}
		PopStackElement();
		sElementContents.erase();
	}
	catch (...) { return -1; }

return 0;
}

//
// Characters insige a element
//
INT_32 XMLConfigHandler::Characters(CCHAR_P         sData,
                                    const UINT_32 & iLength,
                                    const UINT_32 & iLevel,
                                    const UINT_32 & iLine,
                                    const UINT_32 & iColumn)   throw()
{
	try
	{
		sElementContents.append(sData, iLength);
	}
	catch(...) { return -1; }

return 0;
}

//
// XML Parse Error Handler
//
void XMLConfigHandler::ParseError(CCHAR_P         sReason,
                                  const UINT_32 & iLevel,
                                  const UINT_32 & iLine,
                                  const UINT_32 & iColumn)     throw()
{
#ifdef _DEBUG
fprintf(stderr, "ERROR: %s (level %d) at line %d, column %d\n", sReason, iLevel, iLine, iColumn);
#endif
}

} // namespace FTSS
// End.
